package com.czh.framework.security.filter;

import com.czh.common.constant.CacheConstants;
import com.czh.common.date.RedisCache;
import com.czh.framework.security.authentication.JwtAuthentication;
import com.czh.framework.security.web.UserDetailsEntity;
import com.czh.framework.security.web.service.TokenService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.czh.common.constant.CacheConstants.LOGIN_REDIS_KEY;
import static com.czh.common.constant.CacheConstants.TOKEN_MIN_TIME_OUT_MINUTE;
import static com.czh.framework.security.contant.SecurityConstant.AUTH_HEADER;

public class JwtAuthenticationFilter extends OncePerRequestFilter {


    RedisCache redisCache;

    AuthenticationManager authenticationManager;

    public JwtAuthenticationFilter(RedisCache redisCache, AuthenticationManager authenticationManager) {
        this.redisCache = redisCache;
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(AUTH_HEADER);

        if (token == null || token.equals("")) {
            filterChain.doFilter(request,response);
            return;
        }
        JwtAuthentication jwtAuthentication = new JwtAuthentication(token);

        try {
            authenticationManager.authenticate(jwtAuthentication);
        }catch (Exception e) {
            throw new BadCredentialsException("GGG");
        }finally {
            //需要往 继续往下走 到 ExceptionTransactionFilter 进行异常处理。。。
            filterChain.doFilter(request,response);
        }
    }
}
